<template>
  <div class="attendance-page">
    <!-- 日期选择器 -->
    <van-cell title="选择单个日期" :value="selectedDate" @click="showCalendar = true" />
    <van-calendar
        v-model:show="showCalendar"
        :min-date="minDate"
        :max-date="maxDate"
        @confirm="onDateConfirm"
        color="rgba(101, 242, 13, 0.622)"
    />
    <div v-if="role !== 3" class="choose">
      <!-- 学生选择框 -->
      <van-field
          v-model="studentName"
          is-link
          readonly
          label="学生姓名"
          placeholder="选择学生"
          @click="showPicker = true"
      />
      <!-- 重置按钮 -->
      <van-button
          type="danger"
          @click="resetSelection"
          size="small"
          round
          color="rgba(101, 242, 13, 0.622)"
          icon-position="right"
      >
        <van-icon name="replay" />
      </van-button>
    </div>
    <van-popup v-model:show="showPicker" round position="bottom">
      <van-picker :columns="studentOptions" @cancel="showPicker = false" @confirm="onStudentConfirm" />
    </van-popup>

    <!-- 添加考勤按钮 -->
    <div v-if="role !== 2" class="add-attendance-button" >
      <van-button type="primary" @click="showAddAttendancePopup = true" size="small" round color="rgba(101, 242, 13, 0.622)">添加考勤</van-button>
    </div>
    <!-- 添加考勤表单 -->
    <van-popup v-model:show="showAddAttendancePopup" round position="bottom">
      <div>
        <van-field
            v-model="newAttendance.studentName"
            label="学生姓名"
            is-link
            readonly
            @click="showStudentPicker = true"
            placeholder="选择学生"
        />
        <van-popup v-model:show="showStudentPicker" round position="bottom">
          <van-picker :columns="studentOptions" @confirm="onNewStudentConfirm" @cancel="showStudentPicker = false" />
        </van-popup>

        <van-field
            v-model="newAttendance.statusName"
            label="状态"
            is-link
            readonly
            @click="showStatusPicker = true"
            placeholder="选择状态"
        />
        <van-popup v-model:show="showStatusPicker" round position="bottom">
          <van-picker :columns="statusOptions" @confirm="onNewStatusConfirm" @cancel="showStatusPicker = false" />
        </van-popup>

        <van-field
            v-model="newAttendance.time"
            label="时间"
            is-link
            readonly
            @click="showNewDatePicker = true"
            placeholder="选择时间"
        />
        <van-popup v-model:show="showNewDatePicker" round position="bottom">
          <van-datetime-picker
              v-model="newDate"
              type="datetime"
              title="选择完整时间"
              :min-date="minDate"
              :max-date="maxDate"
              @confirm="onNewDateConfirm"
              @cancel="showNewDatePicker = false"
          />
        </van-popup>

        <van-field label="文件上传">
          <template #input>
            <van-uploader v-model="newAttendance.photo" multiple :max-count="1" />
          </template>
        </van-field>

        <van-button round block type="info" native-type="submit" @click="handleAddAttendance">提交</van-button>
        <van-button round block type="warning" @click="showAddAttendancePopup = false">取消</van-button>
      </div>
    </van-popup>

    <!-- 编辑考勤表单 -->
    <van-popup v-model:show="showEditAttendancePopup" round position="bottom">
      <div>
        <van-field
            v-model="editAttendance.studentName"
            label="学生姓名"
            is-link
            readonly
            @click="showEditStudentPicker = true"
            placeholder="选择学生"
        />
        <van-popup v-model:show="showEditStudentPicker" round position="bottom">
          <van-picker :columns="studentOptions" @confirm="onEditStudentConfirm" @cancel="showEditStudentPicker = false" />
        </van-popup>

        <van-field
            v-model="editAttendance.statusName"
            label="状态"
            is-link
            readonly
            @click="showEditStatusPicker = true"
            placeholder="选择状态"
        />
        <van-popup v-model:show="showEditStatusPicker" round position="bottom">
          <van-picker :columns="statusOptions" @confirm="onEditStatusConfirm" @cancel="showEditStatusPicker = false" />
        </van-popup>

        <van-field
            v-model="editAttendance.time"
            label="时间"
            is-link
            readonly
            @click="showEditDatePicker = true"
            placeholder="选择时间"
        />
        <van-popup v-model:show="showEditDatePicker" round position="bottom">
          <van-datetime-picker
              v-model="editDate"
              type="datetime"
              title="选择完整时间"
              :min-date="minDate"
              :max-date="maxDate"
              @confirm="onEditDateConfirm"
              @cancel="showEditDatePicker = false"
          />
        </van-popup>

        <!--<van-field label="文件上传">
          <template #input>
            <van-uploader v-model="editAttendance.photo" multiple :max-count="1" />
          </template>
        </van-field>-->
        <div v-if="editAttendance.url" class="uploaded-image">
          <img :src="getFullImageUrl(editAttendance.url)" alt="Uploaded Image" class="attendance-image" />
        </div>

        <van-button round block type="info" native-type="submit" @click="handleUpdateAttendance">提交</van-button>
        <van-button round block type="warning" @click="showEditAttendancePopup = false">取消</van-button>
      </div>
    </van-popup>

    <div class="attendance-content">
      <div class="attendance-list-container">
        <SwipeCell
            v-for="attendance in filteredAttendance"
            :key="attendance.id"
            :right-width="80"
            :left-width="0"
        >
          <template #right>
            <div class="swipe-actions" v-if="role !== 2">
              <van-button
                  square
                  type="primary"
                  icon="edit"
                  @click="triggerEdit(attendance)"
              ></van-button>
              <van-button
                  square
                  type="danger"
                  icon="delete"
                  @click="confirmDelete(attendance.id)"
              ></van-button>
            </div>
          </template>
          <div class="attendance-item" @click="selectAttendance(attendance)">
            <div class="attendance-title-box">
              <div class="attendance-info-container">
                <div class="attendance-info">
                  <div class="attendance-title">学生姓名: {{ attendance.studentName }}</div>
                  <div class="attendance-detail">
                    <div class="attendance-preview">
                      <div class="attendance-preview-content">
                        <van-tag :type="attendance.status === 1 ? 'success' : 'danger'" size="large">
                          状态: {{ formatStatus(attendance.status) }}
                        </van-tag>
                      </div>
                    </div>
                    <span class="attendance-date" style="color: gray; font-size: smaller;">
                      时间: {{ formatDate(attendance.time) }}
                    </span>
                  </div>
                </div>
                <div class="attendance-media">
                  <img
                      v-if="attendance.url"
                      :src="getFullImageUrl(attendance.url)"
                      alt="Attendance Image"
                      class="attendance-image"
                      @click="triggerFileInput(attendance.studentId, attendance.time)"
                  />
                  <input type="file" ref="fileInput" @change="onFileChange" style="display: none;" />
                </div>
              </div>
            </div>
          </div>
        </SwipeCell>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import axios from 'axios';
import { getOssPrefix } from '@/v-api/properties';
import { Toast, Dialog, SwipeCell } from 'vant';

const attendanceList = ref([]);
const selectedDate = ref('');
const showCalendar = ref(false);
const studentName = ref('');
const studentId = ref(null);
const showPicker = ref(false);
const studentOptions = ref([]);
const statusOptions = ref([{ text: '未签到', value: 0 }, { text: '已签到', value: 1 }]);
const minDate = new Date(2020, 0, 1);
const maxDate = new Date();
const selectedAttendance = ref(null);
const prefix = getOssPrefix();
const role = ref(null);
const filteredAttendance = ref([]);
const showAddAttendancePopup = ref(false);
const showEditAttendancePopup = ref(false);
const showStudentPicker = ref(false);
const showStatusPicker = ref(false);
const showNewDatePicker = ref(false);
const showEditStudentPicker = ref(false);
const showEditStatusPicker = ref(false);
const showEditDatePicker = ref(false);
const newAttendance = reactive({ studentId: '', studentName: '', status: '', statusName: '', time: '', photo: [] });
const editAttendance = reactive({});

const newDate = ref(new Date());
const editDate = ref(new Date());

const getTodayDate = () => {
  const today = new Date();
  return today.toISOString().split('T')[0];
};

onMounted(async () => {
  selectedDate.value = getTodayDate();
  maxDate.setDate(maxDate.getDate());
  await fetchRole();
  await fetchAttendance();
  await fetchStudentOptions();
  filterAttendanceByDate(); // 在页面加载时过滤当天的考勤信息
});

const fetchRole = async () => {
  try {
    const response = await axios.get('/api/student/role');
    role.value = response.data.data.role;
    if (role.value === 3) {
      studentId.value = response.data.data.id;
    }
  } catch (error) {
    console.error('Failed to fetch role:', error);
  }
};

const fetchAttendance = async () => {
  try {
    const response = await axios.get('/api/attendance');
    const attendanceData = response.data.data.map(item => ({
      ...item,
      time: new Date(item.time)
    }));
    attendanceList.value = attendanceData;
    filterAttendanceByDate();
  } catch (error) {
    console.error('Failed to fetch attendance list:', error);
  }
};

const fetchStudentOptions = async () => {
  try {
    const response = await axios.get('/api/student/by-teacher-or-parent');
    const students = response.data.data;
    studentOptions.value = students.map(student => ({
      text: student.studentName,
      value: student.studentId
    }));

    attendanceList.value.forEach(attendance => {
      const student = students.find(s => s.studentId === attendance.studentId);
      if (student) {
        attendance.studentName = student.studentName;
      }
    });
  } catch (error) {
    console.error('Failed to fetch student options:', error);
  }
};

const onStudentConfirm = (student) => {
  studentName.value = student.text;
  studentId.value = student.value;
  showPicker.value = false;
  filterAttendanceByStudentId(student.value);
};

const filterAttendanceByStudentId = (studentId) => {
  filteredAttendance.value = attendanceList.value.filter(item => item.studentId === studentId);
};

const resetSelection = () => {
  studentName.value = '';
  studentId.value = null;
  filterAttendanceByDate();
};

const filterAttendanceByDate = () => {
  if (!selectedDate.value) {
    return;
  }
  filteredAttendance.value = attendanceList.value.filter(item => {
    const itemDate = new Date(item.time);
    return itemDate.toISOString().split('T')[0] === selectedDate.value;
  });
};

const onDateConfirm = (date) => {
  date.setDate(date.getDate() + 1);
  selectedDate.value = date.toISOString().split('T')[0];
  showCalendar.value = false;
  filterAttendanceByDate();
};

const formatDate = (date) => {
  return new Date(date).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  }).replace(/\//g, '-');
};

const formatStatus = (status) => {
  switch (status) {
    case 0:
      return '未签到';
    case 1:
      return '已签到';
    default:
      return '未知';
  }
};

const getFullImageUrl = (url) => {
  return prefix + url;
};

const triggerFileInput = (studentId, time) => {
  selectedAttendance.value = { studentId, time };
  document.querySelector('input[type="file"]').click();
};

const onFileChange = async (event) => {
  const file = event.target.files[0];
  if (file && selectedAttendance.value) {
    try {
      const formData = new FormData();
      formData.append('file', file);
      formData.append('studentId', selectedAttendance.value.studentId);
      formData.append('time', new Date(selectedAttendance.value.time).toISOString());

      const response = await axios.post('/api/attendance/upload', formData);
      const { url } = response.data;

      const attendance = attendanceList.value.find(
          item => item.studentId === selectedAttendance.value.studentId &&
              new Date(item.time).toISOString() === new Date(selectedAttendance.value.time).toISOString()
      );
      if (attendance) {
        attendance.url = url;
      }

      selectedAttendance.value = null;
      event.target.value = '';

      await fetchAttendance();
      await fetchStudentOptions();
      if (studentId.value) {
        filterAttendanceByStudentId(studentId.value);
      } else {
        filterAttendanceByDate();
      }

    } catch (error) {
      console.error('Failed to upload file:', error);
    }
  }
};

const onNewStudentConfirm = (value) => {
  newAttendance.studentId = value.value;
  newAttendance.studentName = value.text;
  showStudentPicker.value = false;
};

const onNewStatusConfirm = (value) => {
  newAttendance.status = value.value;
  newAttendance.statusName = value.text;
  showStatusPicker.value = false;
};

const onNewDateConfirm = (date) => {
  newAttendance.time = formatDate(date);
  showNewDatePicker.value = false;
};

const handleAddAttendance = async (event) => {
  event.preventDefault();
  try {
    const formData = new FormData();
    formData.append('studentId', newAttendance.studentId);
    formData.append('status', newAttendance.status);
    formData.append('time', newAttendance.time);
    if (newAttendance.photo.length > 0) {
      formData.append('file', newAttendance.photo[0].file);
    }
    const response = await axios.post('/api/attendance/add', formData);
    if (response.data.code === 2000) {
      Toast.success('添加成功');
      showAddAttendancePopup.value = false;
      await fetchAttendance();
      await fetchStudentOptions();
      if (studentId.value) {
        filterAttendanceByStudentId(studentId.value);
      } else {
        filterAttendanceByDate();
      }
    } else {
      Toast.fail(response.data.message);
    }
  } catch (error) {
    console.error('Failed to add attendance:', error);
    Toast.fail('添加失败');
  }
};

const onEditStudentConfirm = (value) => {
  editAttendance.studentId = value.value;
  editAttendance.studentName = value.text;
  showEditStudentPicker.value = false;
};

const onEditStatusConfirm = (value) => {
  editAttendance.status = value.value;
  editAttendance.statusName = value.text;
  showEditStatusPicker.value = false;
};

const onEditDateConfirm = (date) => {
  editAttendance.time = formatDate(date);
  showEditDatePicker.value = false;
};

const handleUpdateAttendance = async (event) => {
  event.preventDefault();
  try {
    const formData = new FormData();
    formData.append('id', editAttendance.id);
    formData.append('studentId', editAttendance.studentId);
    formData.append('status', editAttendance.status);
    formData.append('time', editAttendance.time);
    if (editAttendance.photo.length > 0) {
      formData.append('file', editAttendance.photo[0].file);
    }
    const response = await axios.put('/api/attendance/update', formData);
    if (response.data.code === 2000) {
      Toast.success('更新成功');
      showEditAttendancePopup.value = false;
      await fetchAttendance();
      await fetchStudentOptions();  // 更新后重新加载学生选项
      filterAttendanceByDate(); // 保持当前查询结果
      if (studentId.value) {
        filterAttendanceByStudentId(studentId.value);
      }
    } else {
      Toast.fail(response.data.message);
    }
  } catch (error) {
    console.error('Failed to update attendance:', error);
    Toast.fail('更新失败');
  }
};

const confirmDelete = async (id) => {
  Dialog.confirm({
    title: '删除考勤记录',
    message: '确定要删除这条考勤记录吗？',
  }).then(async () => {
    try {
      const response = await axios.delete(`/api/attendance/delete/${id}`);
      if (response.data.code === 2000) {
        Toast.success('删除成功');
        await fetchAttendance();
        await fetchStudentOptions();
        if (studentId.value) {
          filterAttendanceByStudentId(studentId.value);
        } else {
          filterAttendanceByDate();
        }
      } else {
        Toast.fail(response.data.message);
      }
    } catch (error) {
      console.error('Failed to delete attendance:', error);
      Toast.fail('删除失败');
    }
  }).catch(() => {
    // on cancel
  });
};

const triggerEdit = (attendance) => {
  const student = studentOptions.value.find(student => student.value === attendance.studentId);
  editAttendance.id = attendance.id;
  editAttendance.studentId = attendance.studentId;
  editAttendance.studentName = student ? student.text : '';
  editAttendance.status = attendance.status;
  editAttendance.statusName = attendance.status === 1 ? '已签到' : '未签到';
  editAttendance.time = formatDate(new Date(attendance.time));
  editAttendance.photo = [];
  editAttendance.url = attendance.url;
  showEditAttendancePopup.value = true;
};

const selectAttendance = (attendance) => {
  selectedAttendance.value = attendance;
};
</script>

<style scoped>
.attendance-content {
  margin-top: 20px;
  padding: 10px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
}

.attendance-item {
  border-bottom: 1px solid #ddd;
  padding-bottom: 10px;
  margin-bottom: 10px;
}

.attendance-title {
  font-size: 20px;
  margin-bottom: 5px;
}

.attendance-info {
  font-size: 12px;
  color: #666;
  margin-bottom: 10px;
}

.attendance-date {
  margin-right: 20px;
}

.attendance-title-box {
  border: 1px solid #ddd;
  padding: 10px;
  border-radius: 4px;
  margin-bottom: 10px;
}

.attendance-info-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.attendance-image {
  max-width: 150px;
  max-height: 150px;
  border-radius: 4px;
  cursor: pointer;
}

.choose {
  display: flex;
  align-items: center;
  gap: 10px;
}

.add-attendance-button {
  margin-bottom: 10px;
}

.swipe-actions {
  display: flex;
  flex-direction: column;
}

.uploaded-image {
  margin-top: 10px;
  text-align: center;
}

.uploaded-image img {
  max-width: 100%;
  max-height: 150px;
}
</style>
